package com.zyf.lj.controller;

import com.zyf.lj.entity.News;
import com.zyf.lj.service.NewsService;
import com.zyf.lj.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @GetMapping("/list")
    public List<News> getNewsList() {
        return newsService.getAllNews();
    }

    @PostMapping("/add")
    public Result<News> createNews(@RequestBody News news, @RequestAttribute("userId") Integer userId) {
        news.setUserId(userId);
        newsService.createNews(news);
        return Result.success(news);
    }

    @GetMapping("/detail/{id}")
    public Result<News> getNewsDetail(@PathVariable Integer id) {
        News news = newsService.getNewsById(id);
        if (news != null) {
            return Result.success(news);
        } else {
            return Result.fail("新闻不存在");
        }
    }

    @GetMapping("/latest")
    public List<News> getLatestNews() {
        return newsService.getLatestNews(5); // 获取最新5条新闻
    }

    @GetMapping("/my")
    public Result<List<News>> getMyNews(@RequestAttribute("userId") Integer userId) {
        List<News> myNews = newsService.getNewsByUserId(userId);
        return Result.success(myNews);
    }

    @PutMapping("/update")
    public Result<Void> updateNews(@RequestBody News news, @RequestAttribute("userId") Integer userId) {
        news.setUserId(userId); // 确保操作的是自己的新闻
        if (newsService.updateNews(news)) {
            return Result.success();
        } else {
            return Result.fail("更新新闻失败或无权限");
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result<Void> deleteNews(@PathVariable Integer id, @RequestAttribute("userId") Integer userId) {
        if (newsService.deleteNews(id, userId)) {
            return Result.success();
        } else {
            return Result.fail("删除新闻失败或无权限");
        }
    }
} 